package br.com.foxline.atlasmobile.dao;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Context;
import br.com.foxline.atlasmobile.entities.Dne;

import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.dao.RawRowMapper;

public class DneDao extends GenericDao<Dne> {

	private Context context;

	public DneDao(Context context) {
		super(context, new Dne());
		this.context = context;
	}

	public Boolean exist(Long id){
		if(find(id) == null){
			return false;
		}
		return true;
	}
	public Dne getDne(String cep) {
		Dne result = null;
		try {
			result = getDao().queryBuilder().where().like("cep", cep)
					.queryForFirst();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public Date getLastDateUpdate() {
		GenericRawResults<Date> r = null;
		try {
			r = getDao().queryRaw("Select MAX(d. updateAt) from dne d",
					new RawRowMapper<Date>() {

						public Date mapRow(String[] columnName,
								String[] resultColumns) throws SQLException {
							SimpleDateFormat format = new SimpleDateFormat(
									"yyyy-MM-dd HH:mm:ss.SSS");
							try {
								return format.parse(resultColumns[0]);
							} catch (ParseException e) {
								e.printStackTrace();
								return null;
							}
						};
					});
			List<Date> result = r.getResults();
			if (result == null || result.isEmpty()) {
				return null;
			}
			return result.get(0);

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}
}
